


def handle_ner_res(datas):
    print(f'datas: {datas}')
    entities = []
    relations = []
    cts = 1000000
    for data in datas:
        for key, values in data.items():
            for value in values:
                cur_ids = cts
                entit = {
                    'id': cts,
                    'label': key,
                    'start_offset': value['start'],
                    'end_offset': value['end']
                }
                cts += 1
                entities.append(entit)
                if 'relation' not in value:
                    continue
                for sub_key, items in value.get('relations', {}).items():
                    for item in items:
                        sub_ids = cts
                        sub_entit = {
                            'id': sub_ids,
                            'label': sub_key,
                            'start_offset': item['start'],
                            'end_offset': item['end']
                        }
                        entities.append(sub_entit)
                        cts += 1

                        # cur_rela = {"id":cts,"from_id":sub_ids,"to_id":cur_ids,"type":sub_key}
                        cur_rela = {"id":cts,"from_id":cur_ids,"to_id":sub_ids,"type":sub_key}
                        relations.append(cur_rela)
                        cts +=1
    return {'entities': entities, 'relations': relations}

def ner_res2doccano_label(text, ner_res, id=None):
    res = handle_ner_res(ner_res)
    res['text'] = text
    res['id'] = id
    return res


if __name__ == '__main__':
    pass